{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "8e327e09-4571-427b-ba73-af0112e11956",
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "import numpy as np\n",
    "import statsmodels.api as sm\n",
    "from linearmodels.panel import PanelOLS\n",
    "import matplotlib.pyplot as plt\n",
    "import seaborn as sns\n",
    "from scipy.stats import ttest_ind"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "473103b4-90f6-4c0f-85ae-a78812a5259f",
   "metadata": {},
   "source": [
    "# Figure 1"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c8b7d8f5-add5-4188-8ffc-4cda8b7d2c63",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Load the dataset\n",
    "df = pd.read_csv(r\"E:\\df_figure_1.csv\")\n",
    "\n",
    "# Compute yearly averages for all relevant indices\n",
    "df_yearly_avg = df.groupby(\"Year\")[[\"Heat_Index\", \"Environment_Stress_Index\", \"WBGT_JME\"]].mean().reset_index()\n",
    "\n",
    "# Create subplots for each index\n",
    "fig, axs = plt.subplots(3, 1, figsize=(14, 13), sharex=True, constrained_layout=True)\n",
    "\n",
    "# Define colors and markers\n",
    "colors = ['red', 'blue', 'green']\n",
    "markers = ['o', 's', '^']\n",
    "titles = [\"(a) Yearly Average Heat Index\", \"(b) Yearly Average Environment Stress Index\", \"(c) Yearly Average WBGT JME\"]\n",
    "ylabels = [\"Heat Index\", \"Environment Stress Index\", \"WBGT JME\"]\n",
    "\n",
    "for i, column in enumerate([\"Heat_Index\", \"Environment_Stress_Index\", \"WBGT_JME\"]):\n",
    "    axs[i].plot(df_yearly_avg[\"Year\"], df_yearly_avg[column], marker=markers[i], linestyle='dotted', color=colors[i], label=f\"Yearly Average {column}\", linewidth=1.5)\n",
    "    \n",
    "    # Trend line (using numpy polyfit for linear trend)\n",
    "    z = np.polyfit(df_yearly_avg[\"Year\"], df_yearly_avg[column], 1)\n",
    "    p = np.poly1d(z)\n",
    "    axs[i].plot(df_yearly_avg[\"Year\"], p(df_yearly_avg[\"Year\"]), color=colors[i], linewidth=3, label=f\"Trend {column}\")\n",
    "    \n",
    "    axs[i].set_ylabel(ylabels[i], fontsize=16)\n",
    "    axs[i].set_title(titles[i], fontsize=18, pad=17)\n",
    "    axs[i].tick_params(axis='both', labelsize=14)\n",
    "    axs[i].legend(loc='upper left', fontsize=14)  # Updated legend location\n",
    "    axs[i].grid(True)\n",
    "\n",
    "#axs[2].set_xlabel(\"Year\", fontsize=14)\n",
    "plt.savefig(\"yearly_trends_1.jpg\", dpi=600, format='jpg')\n",
    "\n",
    "\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "7fe4fbc3-ad45-42f3-a12f-7f30b44aa111",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "id": "af290688-b108-4bc8-9e0a-ee658b02cfff",
   "metadata": {},
   "source": [
    "# Figure 2"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "93e8fb42-530f-407c-a7a5-fb0621788a7c",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Load the Excel file\n",
    "file_path = r\"E:\\df.xlsx\"\n",
    "xls = pd.ExcelFile(file_path)\n",
    "\n",
    "# Load the data from the sheet\n",
    "df = pd.read_excel(xls, sheet_name='updated_sentiment_analysis')\n",
    "\n",
    "# Compute yearly average mentions of climate change\n",
    "df_yearly = df.groupby('Year')['Heat'].mean().reset_index()\n",
    "\n",
    "# Compute summer (June-August) average mentions of climate change\n",
    "df_summer = df[df['Month'].isin([6, 7, 8])].groupby('Year')['Heat'].mean().reset_index()\n",
    "\n",
    "# Create subplots\n",
    "fig, axs = plt.subplots(1, 2, figsize=(12, 6))  # Increased figure size for spacing\n",
    "plt.subplots_adjust(wspace=0.3, top=0.85)  # Added space between plots and adjusted title padding\n",
    "\n",
    "# Plot yearly climate change mentions trend\n",
    "axs[0].plot(df_yearly['Year'], df_yearly['Heat'], marker='o', linestyle='-', label='Yearly Average Mentions')\n",
    "#axs[0].set_xlabel('Year')\n",
    "axs[0].set_ylabel('Mentions of Heat Wave', size=12)\n",
    "axs[0].set_title('(a) Heat Wave Mentions Trend (Yearly Average)', pad=15, size=13)\n",
    "axs[0].legend(loc='upper left', fontsize=12)\n",
    "axs[0].tick_params(axis='both', labelsize=12)\n",
    "axs[0].grid(True)\n",
    "\n",
    "# Plot summer climate change mentions trend\n",
    "axs[1].plot(df_summer['Year'], df_summer['Heat'], marker='o', linestyle='-', color='r', label='Summer (June-August) Mentions')\n",
    "#axs[1].set_xlabel('Year')\n",
    "axs[1].set_ylabel('Mentions of Heat Wave', size=12)\n",
    "axs[1].set_title('(b) Heat Wave Mentions Trend (Summer: June-August)', pad=15, size=13)\n",
    "axs[1].legend(loc='upper left', fontsize=12)\n",
    "axs[1].tick_params(axis='both', labelsize=12)\n",
    "axs[1].grid(True)\n",
    "\n",
    "plt.savefig(\"yearly_trends_3.jpg\", dpi=600, format='jpg', bbox_inches='tight')  # Ensure full title is visible\n",
    "\n",
    "# Show plots\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "eee9135e-70ee-4ddd-8891-41dbc1d7a5e2",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "id": "191263c7-c62c-442f-aecc-2a68094e729b",
   "metadata": {},
   "source": [
    "# Figure 3"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "4b589f55-e734-4c62-aaaa-758d3be00508",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Load the Excel file\n",
    "file_path = r\"E:\\df.xlsx\"\n",
    "df = pd.read_excel(file_path, sheet_name='updated_sentiment_analysis')\n",
    "\n",
    "# Create subplots\n",
    "fig, axs = plt.subplots(1, 2, figsize=(12, 4))\n",
    "plt.subplots_adjust(wspace=0.3)  # Add spacing between plots\n",
    "\n",
    "# KDE Plot\n",
    "sns.kdeplot(df['Sentiment_Score_Climate_Change_Conservative'], label='Conservative Sentiment', shade=True, color='blue', ax=axs[0])\n",
    "sns.kdeplot(df['Sentiment_Score_Climate_Change_Liberal'], label='Liberal Sentiment', shade=True, hatch='//', color='red', ax=axs[0])  # Added hatch pattern for distinction\n",
    "axs[0].set_xlabel('Sentiment Score', size=14)\n",
    "axs[0].set_ylabel('Density', size=12)\n",
    "axs[0].set_title('(a) Distribution of Sentiment Scores by Political Faction', pad=15, fontsize=13)\n",
    "axs[0].legend()\n",
    "axs[0].grid(True)\n",
    "\n",
    "# Boxplot\n",
    "sns.boxplot(data=df[['Sentiment_Score_Climate_Change_Conservative', 'Sentiment_Score_Climate_Change_Liberal']], ax=axs[1], palette=['blue', 'red'])\n",
    "axs[1].set_xticklabels(['Conservative', 'Liberal'], size=14)\n",
    "axs[1].set_ylabel('Sentiment Score', size=12)\n",
    "axs[1].set_title('(b) Boxplot of Sentiment Scores by Political Faction', pad=15, fontsize=13)\n",
    "axs[1].grid(True)\n",
    "\n",
    "# Add mean and standard deviation text on boxplot\n",
    "for i, column in enumerate(['Sentiment_Score_Climate_Change_Conservative', 'Sentiment_Score_Climate_Change_Liberal']):\n",
    "    mean_value = df[column].mean()\n",
    "    std_value = df[column].std()\n",
    "    axs[1].text(i, mean_value, f'Mean: {mean_value:.2f}\\nStd: {std_value:.2f}', \n",
    "                horizontalalignment='center', verticalalignment='bottom', fontsize=12, color='white')\n",
    "\n",
    "plt.savefig(\"difference_3.jpg\", dpi=600, format='jpg', bbox_inches='tight')  # Ensure full title is visible\n",
    "\n",
    "# Show plots\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "61dab8af-303c-45bd-9d1a-030e8fb5d6cf",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "fb2229a4-643c-44b8-acdc-b4e6e45e31c5",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e489b6fc-cb58-45b9-bd20-b805462e870d",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "283b2a2d-0ef6-4001-9e1a-3efb7dc82b76",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.8"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
